package services

import (
	"context"
	"errors"
	"wxapi/internal/svc"
	"wxapi/models"

	"gitee.com/dromara/carbon/v2"
)

func GetDoctorIdleDate(ctx context.Context, svc *svc.ServiceContext, doctorId int64) ([]string, error) {
	resets := make([]*models.DoctorReset, 0)
	svc.Mysql.Where("doctor_id = ?", doctorId).Find(&resets)

	dates := make([]string, 0)
	count := 7
	for i := 0; i < count; i++ {
		jump := false
		for _, reset := range resets {
			if reset.ResetType == 1 && int64(carbon.Now().AddDays(i).DayOfWeek()) == reset.WeekDay {
				count++
				jump = true
				break
			}
			if reset.ResetType == 2 && carbon.Now().AddDays(i).ToDateString() == reset.ResetDate.ToDateString() {
				count++
				jump = true
				break
			}
		}
		if !jump {

			dates = append(dates, carbon.Now().AddDays(i).Format("Y-m-d"))
		}
	}
	return dates, nil
}

func GetDoctorWorkTime(ctx context.Context, svc *svc.ServiceContext, doctorId int64) ([]string, error) {
	doctor := models.Doctor{}
	svc.Mysql.Model(&models.Doctor{}).Preload("Store").Preload("Store.StoreInterval").Where("id = ?", doctorId).First(&doctor)
	if doctor.Store == nil || doctor.Store.StoreInterval == nil {
		return nil, errors.New("门店信息不存在")
	}

	store := doctor.Store
	interval := store.StoreInterval
	openTime := carbon.Now().SetTime(store.StoreOpenTime.Hour(), store.StoreOpenTime.Minute(), 0)
	closeTime := carbon.Now().SetTime(store.StoreCloseTime.Hour(), store.StoreCloseTime.Minute(), 0)

	times := make([]string, 0)
	currentTime := openTime
	for {
		times = append(times, currentTime.Format("H:i"))
		currentTime = currentTime.AddHours(int(interval.IntervalHour)).AddMinutes(int(interval.IntervalMinute))
		if currentTime.Gt(closeTime) {
			break
		}
	}

	return times, nil
}
